import BaseService from '../base';
import _ from 'lodash';
import {getLogger} from '../../utils';

class OrgService extends BaseService {


    /**
     * get one organization
     * @param id
     * @param callback
     */
    get(id, callback) {

        let me = this;
        let exec = function () {
            return me.buildExecute((client, onFulfilled, onRejected) => {
                client.collection('org').find({id: parseInt(id)}).limit(1).next(function (err, doc) {
                    if (err) {
                        return onRejected(err);
                    }
                    onFulfilled(doc);
                });
            });
        }

        exec().then(res => {
            getLogger().info(res);
            callback(null, res);
        }).catch(err => {
            callback(err, null);
        });

    }

    /**
     * list organizations
     * @param param
     * @param callback
     */
    list(param, callback) {

        let query = _.create({}, param);
        query = _.omit(query, 'page', 'size');

        let page = param.page || 1;
        let size = param.size || 0;
        let me = this;

        let tasks = [
            function () {
                return me._getOrgs(query, page, size)
            },
            function () {
                return me._count(query)
            }
        ];

        super.allExecute(tasks, (results)=> {
            let pagination = {
                current: page,
                total: results[1],
                pageSize: size
            }
            let res = {
                items: results[0],
                pagination: pagination
            };
            callback(null, res);

        }, (err)=> {
            callback(err, null);
        });


    }

    /**
     * 获得组织列表
     * @param query
     * @param page
     * @param size
     * @returns {一个Promise执行对象}
     * @private
     */
    _getOrgs(query, page, size) {

        return super.buildExecute((client, onFulfilled, onRejected)=> {
            client.collection('org').find(query).skip((page - 1) * size).limit(size).toArray(function (err, doc) {
                if (err) {
                    return onRejected(err);    //错误的时候调用
                }
                onFulfilled(doc);       //成功的时候调用
            });
        });

    }

    /**
     * 获得组织的数量
     * @param query
     * @returns {一个Promise执行对象}
     * @private
     */
    _count(query) {
        return super.buildExecute((client, onFulfilled, onRejected)=> {
            client.collection('org').count(query, function (err, count) {
                if (err) {
                    onRejected(err);
                    return;
                }
                onFulfilled(count);
            });
        });
    }


}

export default new OrgService();
